package com.test.leetcode;

/**
 * https://leetcode.cn/problems/longest-common-subsequence/description/
 * @author sujiafa
 * @date 2025/4/3
 */
public class n1143_最长公共子序列 {


    public int longestCommonSubsequence(String text1, String text2) {

        // 线性DP知识一例题
        int lengthText1 = text1.length();
        int lengthText2 = text2.length();
        // dp[i][j]表示text1中前i个元素组成的子字符串str1与text2中前j个元素组成的子字符串str2的最长公共子序列长度为dp[i][j]
        int[][] dp = new int[lengthText1 + 1][lengthText2 + 1];
        for (int i = 1; i < lengthText1 + 1; i++) {
            for (int j = 1; j < lengthText2 + 1; j++) {
                if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }

        return dp[lengthText1][lengthText2];
    }
}
